package jh.com.jhappbf.weight.query;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.fragment.AbFragment;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.SettingModel;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.DisplayUtil;
import jh.com.jhappbf.utils.ExpressionUtils;
import jh.com.jhappbf.utils.FileImport;
import jh.com.jhappbf.utils.JsonHelper;

import static android.content.Context.MODE_PRIVATE;

/**
 * @author : wwh
 * e-mail : 953889276@qq.com
 * time   : 2019/10/23 18:41
 * desc   :
 */
public class QueryWeightListView2 extends AbFragment {
    private List<JSONObject> mShowData = new ArrayList<>(); //列表显示的数据
    private List<JSONObject> mDataSource = new ArrayList<>(); //数据源
    private MyBaseAdapter mAdapter; //数据列表适配器
    private AbLoadDialogFragment mDialogFragment = null; //进度框
    private List<String> mFields = new ArrayList<>();
    private List<String> mSaverFields = new ArrayList<>();
    private Drawable mHeadDrawable;//列表头下拉框
    private int mCurrentPage = 0;//当前页数
    private int mPageSize = 30; //当前页的大小
    private Context mAppContext;
    private AbPullToRefreshView mRefreshView; // 下拉刷新上拉加载更多
    private LinearLayout mListViewHeader; // 数据标题
    private ListView mListView; // 数据列表
    private RelativeLayout mErrorContentView; // 网络不给力显示的视图
    private RelativeLayout mContentView; // 显示的数据列表的视图
    private Button mBtnErrRefresh; // 重试
    private Button mBtnSetting; // 设置
    private List<TextView> mTitleTxt ; //列表的表头view
    private final int SETTING = 0X001;
    private String mFlag = "";
    private SettingModel mSettingModel;
    private ArrayList<String> mSelectData = new ArrayList<>();
    private List<JSONObject> newListData = new ArrayList<>();
    private RelativeLayout mExportExcel;
    private Map<String, String> mFieldsMap;

    private String methodName = "queryWeight";
    private ArrayList<String> param;
    private ArrayList<String> value;
    private int curPosition = 10000;

    /**
     * 最大列宽(dp)
     */
    private int maxColumnWidth = 200;
    /**
     * 最小列宽(dp)
     */
    private int minColumnWidth = 60;
    /**
     * 记录每列最大宽度
     */
    private ArrayList<Integer> mColumnMaxWidths = new ArrayList<>();
    private float mTextViewSize = 15;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Intent i = getActivity().getIntent();

        if (i != null) {
            mFlag = i.getStringExtra("flag");
            mSettingModel = i.getParcelableExtra("data");
        }
        View v = inflater.inflate(R.layout.query_weight_listview_activity, null);
        initView(v);
        return v;
    }

    /**
     * 初始化
     */
    private void initView(View v) {
        param = new ArrayList<>();
        value = new ArrayList<>();
        mAppContext = getActivity();
        mFieldsMap = new LinkedHashMap<>();
        mTitleTxt = new ArrayList<>();
        mFieldsMap.put("序号", "orderNum");
        mFieldsMap.put("编号", "id");
        mFieldsMap.put("车号", "Platenumber");
        mFieldsMap.put("类型", "Type");
        mFieldsMap.put("货名", "Cargoname");
        mFieldsMap.put("单位", "Specification");

        mFieldsMap.put("发货", "Consignor");
        mFieldsMap.put("收货", "Consignee");
        mFieldsMap.put("合同号", "S4");
        mFieldsMap.put("毛重", "Gross");
        mFieldsMap.put("皮重", "Tare");
        mFieldsMap.put("净重", "Net");
        mFieldsMap.put("单价", "Price");
        mFieldsMap.put("金额", "Amount");
//        mFieldsMap.put("日期", "sDate");
//        mFieldsMap.put("时间", "sTime");
        mFieldsMap.put("毛重时间", "GrossTime");
        mFieldsMap.put("皮重时间", "TareTime");


        for (Entry<String, String> entry : mFieldsMap.entrySet()) {
            mFields.add(entry.getKey());
            mSaverFields.add(entry.getValue());

        }
//        WindowManager wm = getActivity().getWindowManager();
//        DisplayMetrics metrics = new DisplayMetrics();
//        wm.getDefaultDisplay().getMetrics(metrics);
        mHeadDrawable = ContextCompat.getDrawable(getActivity(), R.mipmap.down_select);
        mHeadDrawable.setBounds(0, 0, mHeadDrawable.getMinimumWidth(), mHeadDrawable.getMinimumHeight());

        mContentView = v.findViewById(R.id.query_weight_content);
        mErrorContentView = v.findViewById(R.id.query_weight_error_view);
        mRefreshView = v.findViewById(R.id.query_pullToRefreshView);
        mListView = v.findViewById(R.id.query_listView);
        mListViewHeader = v.findViewById(R.id.query_weight_title);
        mBtnErrRefresh = v.findViewById(R.id.query_weight_error_btn);
        mBtnSetting = getActivity().findViewById(R.id.title_right_btn);
        mExportExcel = v.findViewById(R.id.query_weight_export_excel_layout);
        // 重试
        mBtnErrRefresh.setOnClickListener(v1 -> loadFirst());
        mExportExcel.setOnClickListener(view -> {
//            String url = Constant.ServerPath + "outPutFile/query/" + State.mAccount + "查询.xls";
//            new ExportHelper(mDialogFragment, url, getActivity(), "查询").export();
            boolean result = FileImport.generateExcel("查询报表", mShowData, mSaverFields, mFields);
            if (result) {
                Toast.makeText(mAppContext, "导出成功", Toast.LENGTH_SHORT).show();
            }
        });
        // 设置
        mBtnSetting.setOnClickListener(v12 -> {
            Intent i = new Intent(getActivity(), QuerySetting.class);
            i.putExtra("data", mSettingModel);
            startActivityForResult(i, SETTING);
        });
        // 下拉刷新
        mRefreshView.setOnHeaderRefreshListener(view -> refreshTask(mSettingModel));
        // 上拉加载更多
        mRefreshView.setOnFooterLoadListener(view -> loadMoreTask(mSettingModel));
        // 单击数据项
        mListView.setOnItemClickListener((parent, view, position, id) -> {
            curPosition = position;
            mAdapter.notifyDataSetChanged();
        });
        //长按列表显示称重的详细信息
        mListView.setOnItemLongClickListener((parent, view, position, id) -> {
            Intent i = new Intent(getActivity(), QueryWeightDetail.class);
            JSONObject obj = mShowData.get(position);
            String weightId = obj.optString("id");
            i.putExtra("flag", weightId);
            startActivity(i);
            return true;
        });
        // 设置进度条的样式
        mRefreshView.getHeaderView().setHeaderProgressBarDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.progress_circular));
        mRefreshView.getFooterView().setFooterProgressBarDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.progress_circular));
        // 生成数据列表表头
        makeHeader();
        // 加载数据
        loadFirst();
        // 绑定ListView的Adapter
        mAdapter = new MyBaseAdapter();
        mListView.setAdapter(mAdapter);
    }

    private void loadFirst() {
        mDialogFragment = AbDialogUtil.showLoadDialog(getActivity(), R.mipmap.ic_load, "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(() -> {
            mErrorContentView.setVisibility(View.GONE);
            mContentView.setVisibility(View.VISIBLE);
            refreshTask(mSettingModel);
        });
    }

    /**
     * 表头
     */
    private void makeHeader() {
        mListViewHeader.removeAllViews();
        if (mColumnMaxWidths.size() != mFields.size()) {
            initColumnWidth(mFields);
        }
        TableLayout table = new TableLayout(mAppContext);
        TableRow row = new TableRow(mAppContext);
        String columnName;
        for (int index = 0; index < mFields.size(); index++) {
            TextView txt = new TextView(getActivity());
            txt.setTextColor(Color.BLACK);
            txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTextViewSize);
            txt.setGravity(Gravity.CENTER);
            txt.setId(index);
            columnName = mFields.get(index);
            txt.setText(columnName);
            txt.setTag(columnName);
            txt.setClickable(true);
            mTitleTxt.add(txt);
            txt.setOnClickListener(this::popupWindow);
            txt.setCompoundDrawables(null, null, mHeadDrawable, null);
            txt.setWidth(DisplayUtil.dip2px(mAppContext, mColumnMaxWidths.get(index)));
            LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            row.addView(txt, layoutParams);
            View splitView = new View(getActivity());
            LayoutParams splitViewParams = new LayoutParams(DisplayUtil.dip2px(getActivity(), 1), LayoutParams.MATCH_PARENT);
            splitView.setLayoutParams(splitViewParams);
            splitView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.gray));
            row.addView(splitView);
        }
        table.addView(row);
        mListViewHeader.addView(table);
    }

    private void initColumnWidth(List<String> stringList) {
        for (int i = 0; i < stringList.size(); i++) {
            TextView textView = new TextView(mAppContext);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTextViewSize);
            textView.setText(stringList.get(i));
            textView.setGravity(Gravity.CENTER);
            //设置布局
            LayoutParams textViewParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            textView.setLayoutParams(textViewParams);
            int width = measureTextWidth(textView, stringList.get(i))+DisplayUtil.px2dip(mAppContext, mHeadDrawable.getMinimumWidth());
//            int width = measureTextWidth(textView, stringList.get(i))+11;
            if (mColumnMaxWidths.size() == mFields.size()) {
                int oldWidth = mColumnMaxWidths.get(i);
                if (width > oldWidth) {
                    mColumnMaxWidths.set(i, width);
                }
            } else {
                mColumnMaxWidths.add(width);
            }
        }
    }

    /**
     * 弹出选择框
     *
     * @param v 当前View
     */
    private void popupWindow(View v) {
        if (v instanceof TextView) {
            final TextView txt = (TextView) v;
            String columnName = (String) txt.getTag();
            String columnField = mFieldsMap.get(columnName);
            if (!TextUtils.isEmpty(columnField)) {
                mSelectData.clear();
                //mSelectData.add(columnName);
                mSelectData.add("全部");
                String item;
                for (JSONObject jsonObject : mDataSource) {
                    item = jsonObject.optString(columnField);
                    if (!mSelectData.contains(item)) {
                        mSelectData.add(item);
                    }
                }
                if (mSelectData.size() > 1) {
                    mSelectData.remove(1);
                }
                /**
                 * mSelectData.toArray(new String[0])
                 *无参数的toArray()转换后的数组类型是Object[],而把Object[]给cast成String[]还是很麻烦的
                 *其实用带参数的toArray就好了<T> T[] toArray(T[] a);      String[] a = c.toArray(new String[0]);
                 *用new String[0]只是为了指定函数的形参数，0是为了节省空间，最终返回的String[]的长度是由你的list存储内容的长度决定
                 * 此方法允许在输出数组的运行时类型上进行精确控制，并且在某些情况下，可以用来节省分配开销
                 * list.toArray(new int[0]);//转化成int数组
                 */
                new Builder(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
                        .setTitle(columnName + "选择")
                        .setItems(mSelectData.toArray(new String[0]), (dialog, which) -> {
                            if (which == 0) {
                                txt.setText(columnName);
                            } else {
                                txt.setText(mSelectData.get(which));
                            }
                            filterData();
                        }).create().show();
            }
        }
    }

    private void refreshView() {
        mShowData = mDataSource;
        if(mShowData.size()>0){
            getSum();
            measureMaxColumnWidth(mShowData);
            setHeaderWidth();
        }

        mAdapter.notifyDataSetChanged();
    }

    /**
     * 过滤,合计
     */
    private void filterData() {
        String valStr;
        String tagStr;
        Map<String, String> mHashMap = new HashMap<>();
        for (TextView txt : mTitleTxt) {
            valStr = txt.getText().toString();
            tagStr = (String) txt.getTag();
            if (!valStr.equals(tagStr)) {
                mHashMap.put(tagStr, valStr);
            }
        }
        if (mHashMap.size() > 0) {
            mShowData = new ArrayList<>();
            JSONObject mObject;
            Map<String, Float> sumFieldsMap = new HashMap<>();
            sumFieldsMap.put("Gross", 0f);
            sumFieldsMap.put("Tare", 0f);
            sumFieldsMap.put("Net", 0f);
        //    sumFieldsMap.put("Amount", 0f);
            for (int index = 0; index < mDataSource.size(); index++) {
                mObject = mDataSource.get(index);
                int temp = 0;
                for (Entry<String, String> entry : mHashMap.entrySet()) {
                    if (!mObject.optString(mFieldsMap.get(entry.getKey())).equals(entry.getValue())) {
                        break;
                    }
                    temp++;
                }
                if (temp == mHashMap.size()) {
                    fieldsSum(mObject, sumFieldsMap);
                    mShowData.add(mObject);
                }
            }
            resultSum(sumFieldsMap);
            setHeaderWidth();
            mAdapter.notifyDataSetChanged();
        } else {
            mShowData = mDataSource;
            if(mShowData.size()>0){
                getSum();
            }

            mAdapter.notifyDataSetChanged();
        }
    }

    private void setHeaderWidth() {
        for (int i = 0; i < mTitleTxt.size(); i++) {
            mTitleTxt.get(i).setWidth(DisplayUtil.dip2px(mAppContext, mColumnMaxWidths.get(i)));
        }
    }

    private void measureMaxColumnWidth(List<JSONObject> jsonObjects) {
        for (int i = 0; i < jsonObjects.size(); i++) {
            List<String> strings = new ArrayList<>();
            for (String mSaverField : mSaverFields) {
                strings.add(jsonObjects.get(i).optString(mSaverField));
            }
            initColumnWidth(strings);
        }
    }

    private void fieldsSum(JSONObject mObject, Map<String, Float> sumFieldsMap) {
        for (Entry<String, Float> entry : sumFieldsMap.entrySet()) {
            String str = mObject.optString(entry.getKey());
            if (ExpressionUtils.isNumber(str)) {
                float value = entry.getValue() + Float.parseFloat(str);
                sumFieldsMap.put(entry.getKey(), value);
            }
        }
    }

    private void resultSum(Map<String, Float> sumFieldsMap) {
        JSONObject sumObject = new JSONObject();
        try {
            sumObject.put("序号", "合计");
            sumObject.put("Platenumber", "车数:" + mShowData.size());

            DecimalFormat format = new DecimalFormat("0.00");
            for (Entry<String, Float> entry : sumFieldsMap.entrySet()) {
                sumObject.put(entry.getKey(), format.format(entry.getValue()));
            }
            if (mShowData.size() > 0) {
                mShowData.add(0, sumObject);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    ///总合计
    private void getSum() {
        JSONObject obj;
        Map<String, Float> sumFieldsMap = new HashMap<>();
        sumFieldsMap.put("Net", 0f);
        sumFieldsMap.put("Gross", 0f);
        sumFieldsMap.put("Tare", 0f);
 //       sumFieldsMap.put("Amount", 0f);
        for (int index = 0; index < mShowData.size(); index++) {
            obj = mShowData.get(index);
            if (obj.optString("序号").contains("合计")) {
                continue;
            }
            fieldsSum(obj, sumFieldsMap);
        }
        JSONObject firstObj = mShowData.get(0);
        String val = firstObj.optString("序号");
        if (val.contains("合计")) {
            mShowData.remove(0);
        }
        resultSum(sumFieldsMap);
    }

    private void initRequestParams(SettingModel model) {
        param.clear();
        value.clear();
        methodName = "queryWeight";

        param.add("currentPage");
        param.add("startDateTime");
        param.add("endDateTime");
        param.add("cargoname");
        param.add("platenumber");
        param.add("sender");
        param.add("receiver");
        param.add("sitePoint");
        param.add("types");
        param.add("users");
        param.add("company");

        value.add(Integer.toString(mCurrentPage));
        if (model == null) {
            value.add("");
            value.add("");
            value.add("");
            value.add("");
            value.add("");
            value.add("");
            value.add("");
        } else {
            value.add(model.getStartDateTime());
            value.add(model.getEndDateTime());
            value.add(model.getCargoname());
            value.add(model.getPlatenumber());
            value.add(model.getSender());
            value.add(model.getReceiver());
            value.add(model.getSitePoint());
        }
        if("buy".equals(mFlag))
        {
            value.add("采购");
        }
        else if("sale".equals(mFlag))
        {
            value.add("销售");
        }
        else if("out".equals(mFlag))
        {
            value.add("出厂");
        }
        else if("dao".equals(mFlag))
        {
            value.add("内倒");
        }
        else if("ling".equals(mFlag))
        {
            value.add("零售");
        }
        else
        {
            value.add("");
        }
        value.add(State.mAccount + "查询");
        value.add(getCompany());
    }
    private String getCompany() {
        SharedPreferences preferences = getActivity().getSharedPreferences("caption", MODE_PRIVATE);
        return preferences.getString("company", "");
    }
    /**
     * 下拉刷新
     */
    private void refreshTask(SettingModel model) {
        mCurrentPage = 1;
        initRequestParams(model);
        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(getActivity());
            mRefreshView.onHeaderRefreshFinish();
            mErrorContentView.setVisibility(View.GONE);
            mContentView.setVisibility(View.VISIBLE);
            newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null ) {
                mDataSource.clear();
                mDataSource.addAll(newListData);
                if (newListData.size() >= mPageSize) {
                    mCurrentPage++;
                }
                mColumnMaxWidths.clear();
                refreshView();
            }
        };
        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(getActivity());
            mRefreshView.onHeaderRefreshFinish();
            mErrorContentView.setVisibility(View.VISIBLE);
            mContentView.setVisibility(View.GONE);
            mShowData.clear();
            mAdapter.notifyDataSetChanged();
        };
        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }

    /**
     * 上拉加载更多
     */
    private void loadMoreTask(SettingModel model) {
        initRequestParams(model);
        Listener<String> listener = response -> {
            mRefreshView.onFooterLoadFinish();
            if (mDataSource.size() > 0) {
                mDataSource.remove(0);
            }
            if (newListData.size() < mPageSize) {
                mDataSource.removeAll(newListData);
            }
            newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {
                mDataSource.addAll(newListData);
                if (newListData.size() >= mPageSize) {
                    mCurrentPage++;
                }
                refreshView();
            }
        };
        ErrorListener errorListener = error -> {
            mRefreshView.onFooterLoadFinish();
            AbToastUtil.showToast(mAppContext, "数据加载失败！");
        };
        VolleyCallWebService webService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SETTING && data != null) {
            mSettingModel = data.getParcelableExtra("result");
            if (mSettingModel != null) {
                loadFirst();
            }
        }
    }

    private class MyBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mShowData.size();
        }

        @Override
        public Object getItem(int position) {
            return mShowData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("NewApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            TableLayout table;
            if (convertView == null) {
                Context context = getActivity();
                table = new TableLayout(context);
                TableRow row = new TableRow(context);
                for (int index = 0; index < mFields.size(); index++) {
                    TextView txt = new TextView(getActivity());
                    txt.setTextColor(Color.BLACK);
                    txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTextViewSize);
                    txt.setGravity(Gravity.CENTER);
                    txt.setPadding(0, 5, 0, 5);
                    txt.setId(index);
                    LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
                    row.addView(txt, layoutParams);
                    View splitView = new View(getActivity());
                    LayoutParams splitViewParams = new LayoutParams(DisplayUtil.dip2px(getActivity(), 1), LayoutParams.MATCH_PARENT);
                    splitView.setLayoutParams(splitViewParams);
                    splitView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.gray));
                    row.addView(splitView);
                }
                table.addView(row);
                convertView = table;
                convertView.setTag(table);
            } else {
                table = (TableLayout) convertView.getTag();
            }
            JSONObject obj = mShowData.get(position);
            int length = mSaverFields.size();
            //显示表格的一行数据
            for (int i = 0; i < length; i++) {
                TextView textView = table.findViewById(i);
                if (i == 0) {
                    textView.setText(position + "");
                } else {
                    textView.setText(obj.optString(mSaverFields.get(i)));
                }
                textView.setTextColor(Color.BLACK);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTextViewSize);
                textView.setGravity(Gravity.CENTER);
                textView.setWidth(DisplayUtil.dip2px(mAppContext, mColumnMaxWidths.get(i)));
            }
            if (position == curPosition) {
                convertView.setBackgroundColor(Color.GREEN);
            } else {
                convertView.setBackgroundColor(Color.WHITE);
            }
            return convertView;
        }
    }

    /**
     * 根据最大最小值，计算TextView的宽度
     *
     * @param textView
     * @param text
     * @return
     */
    private int measureTextWidth(TextView textView, String text) {
        if (textView != null) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams();
            int width = DisplayUtil.px2dip(mAppContext, layoutParams.leftMargin) +
                    DisplayUtil.px2dip(mAppContext, layoutParams.rightMargin) +
                    getTextViewWidth(textView, text);
            if (width <= minColumnWidth) {
                return minColumnWidth;
            } else if (width > minColumnWidth && width <= maxColumnWidth) {
                return width;
            } else {
                return maxColumnWidth;
            }
        }
        return 0;
    }

    /**
     * 根据文字计算textview的宽度
     *
     * @param view
     * @param text
     * @return
     */
    private int getTextViewWidth(TextView view, String text) {
        if (view != null) {
            TextPaint paint = view.getPaint();
            return DisplayUtil.px2dip(mAppContext, (int) paint.measureText(text));
        }
        return 0;
    }
}
